<template>
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="课程名称">
            <el-input v-model="pageQuery.otherParams.courseName" placeholder="输入课程名称搜索" clearable />
          </el-form-item>
          <el-form-item label="教师姓名">
            <el-input v-model="pageQuery.otherParams.tchName" placeholder="输入教师姓名搜索" clearable />
          </el-form-item>
          <el-form-item label="课程学年">
            <el-select v-model="pageQuery.otherParams.schoolYear" placeholder="选择学年搜索" clearable>
              <el-option v-for="item in schoolYearList" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="课程学期">
            <el-select v-model="pageQuery.otherParams.stage" placeholder="选择学期搜索" clearable>
              <el-option label="第一学期" value="1" />
              <el-option label="第二学期" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="年级">
            <el-input v-model="pageQuery.otherParams.grade" placeholder="输入年级搜索" clearable />
          </el-form-item>
          <el-form-item label="开课类型">
            <el-input v-model="pageQuery.otherParams.courseType" placeholder="输入开课类型搜索" clearable />
          </el-form-item>
          <el-form-item label="学时类型">
            <el-input v-model="pageQuery.otherParams.classHourType" placeholder="输入学时类型搜索" clearable />
          </el-form-item>
          <el-form-item label="课程状态">
            <el-select v-model="pageQuery.otherParams.scoreIsBegin" placeholder="选择课程状态搜索" clearable>
              <el-option label="录入中" value="1" />
              <el-option label="已停录" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <section>
              <el-button type="success" @click.stop="onMoreCilck">高级筛选</el-button>
              <el-button type="primary" icon="Search" @click.stop="getPageInfo">搜 索</el-button>
              <el-button type="warning" icon="RefreshRight" @click.stop="reset">重 置</el-button>
              <el-button v-if="selectType == ''" type="success" icon="Plus" @click="onBatchBegin">批量开始录入</el-button>
              <el-button v-if="selectType == 'begin'" type="success" icon="Plus" @click="onOneKeyBegin">一键开始</el-button>
              <el-button v-if="selectType == ''" type="danger" icon="Minus" @click="onBatchStop">批量停录</el-button>
              <el-button v-if="selectType == 'stop'" type="danger" icon="Minus" @click="onOneKeyStop">一键停录</el-button>
              <el-button v-if="selectType != ''" type="danger" icon="Close" @click="exitSelect">退出选择</el-button>
            </section>
          </el-form-item>
        </el-form>

      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table :border="true" stripe ref="tableRef" :data="tableData.rows" @selection-change="onSeleceChange"
            cell-class-name="table-cell" header-cell-class-name="table-header-cell">
            <el-table-column v-if="selectType != ''" type="selection" :selectable="selectTable" width="55" />
            <el-table-column property="grade" label="年级" width="80" />
            <el-table-column property="schoolYear" label="学年" width="130" />
            <el-table-column property="stage" label="学期" width="100" />
            <el-table-column property="courseCode" label="课程代码" />
            <el-table-column property="courseName" label="课程名称" />
            <el-table-column property="tchName" label="教师名称" />
            <el-table-column property="teachClass" label="教学班" />
            <el-table-column property="classHourType" label="学时类型" />
            <el-table-column property="courseType" label="开课类型" />
            <el-table-column property="stuClass" label="已选人数" width="90">
              <template #default="scope">{{ scope.row.selectedNum }}/{{ scope.row.maxPerson }}</template>
            </el-table-column>
            <el-table-column label="课程状态">
              <template #default="scope">
                <el-tag effect="dark" v-if="scope.row.courseIsBegin == 1" dark size="small" type="success">选课中</el-tag>
                <el-tag effect="dark" v-else size="small" dark type="danger">已停选</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="成绩录入">
              <template #default="scope">
                <el-tag effect="dark" v-if="scope.row.scoreIsBegin == 1" dark size="small" type="success">录入中</el-tag>
                <el-tag effect="dark" v-else size="small" dark type="danger">已停录</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="240">
              <template #default="scope">
                <el-button type="primary" size="small" @click="onCheck(scope.row)">课程详情</el-button>
                <el-button v-if="!scope.row.scoreIsBegin" type="success" size="small" @click="onAdd(scope.row)">开始录入</el-button>
                <el-button v-if="scope.row.scoreIsBegin" type="warning" size="small" @click="onEdit(scope.row)">修改时间</el-button>
                <el-button v-if="scope.row.scoreIsBegin" type="danger" size="small" @click="onStop(scope.row)">停录</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize" :page-sizes="pageSizeOption" :background="true"
            :small="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.totalSize"
            @size-change="onSizeChange" @current-change="onCurrentChange" />
        </span>
      </el-card>
    </globle-linear-border>
    <!-- 弹窗 -->
    <suspense>
      <course-dialog ref="courseDialogRef" @onReGetData="getPageInfo"></course-dialog>
    </suspense>
    <more-params ref="moreParamsRef" @reload="reload"></more-params>
    <begin-dialog ref="beginDialogRef" @onReGetData="getPageInfo" @onBeginBatch="exitSelect"></begin-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { ICoursePageParams, IPageRes, ICourse, APIData, ITch, ICoManageList, ICoManageParams } from '../../../type';
import { useAPI } from '../../../request/api';
import MoreParams from './components/MoreParams.vue';
import BeginDialog from './components/BeginDialog.vue'
//注意!!定义动态引入组件时需要使用defineAsyncComponent，并且在template中需要搭配suspense组件使用,它是一个异步组件解决方案。
const CourseDialog = defineAsyncComponent(() => import('./components/CourseDialog.vue'));

onMounted(() => {
  findAllCourseSchoolYear();
  getPageInfo();
});

const api = useAPI();
const moreParamsRef = ref();
const courseDialogRef = ref();
const beginDialogRef = ref();
const selectType = ref('');
const baseTime = '1970-01-01 00:00:00'; //将时间设置为格林威治时间来停止
const tableRef = ref<InstanceType<typeof ElTable>>();
const schoolYearList = ref([] as { label:string; value:string }[]);

let selectedIdList = [] as Array<string>;
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<ICoursePageParams>({
  otherParams: {
    courseName: '',
    tchName: '',
    schoolYear: '',
    stage: '',
    grade: '',
    courseType: '',
    classHourType: '',
    courseIsDelete: 0,
    scoreIsBegin: ''

    //以下在更多弹窗里面
    // courseCode: '',
    // openCollege: '',
    // place: '',
    // credit: '',
    // week: '',
    // weekDay: '',
    // orderNum: '',
    // teachClass: '',
    // totalHours: '',
    // allowBand: '',
    // workId: ''
    // studentId: '',
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});
const tableData = ref({} as IPageRes);

const reset = () => {
  pageQuery.otherParams = {
    courseName: '',
    tchName: '',
    schoolYear: '',
    stage: '',
    grade: '',
    courseType: '',
    classHourType: '',
    courseIsDelete: 0,
    scoreIsBegin: ''
  }
  pageQuery.pageParams = {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: ''
  }
  getPageInfo();
}

const onCheck = (row: ICourse) => {
  courseDialogRef.value.openDialogByCheck(row.id);
};

const onMoreCilck = () => {
  moreParamsRef.value.open();
}

const reload = (data: any) => {
  tableData.value = data;
}

const onAdd = (row: ICourse) => {
  // if(row.courseIsBegin != 1) {
  //   ElMessage.error('请到选课管理中将该课程开始选课')
  //   return;
  // }
  beginDialogRef.value.openDialogByAdd(row);
};

const onEdit = (row: ICourse) => {
  beginDialogRef.value.openDialogByEdit(row);
};

const onBatchBegin = () => {
  ElMessage({ showClose: true, message: '勾选需要开始成绩录入的课程后，再点击一键开始', type: 'success', duration: 10000 })
  selectType.value = 'begin'
}

const onOneKeyBegin = () => {
  if (selectedIdList.length !== 0) beginDialogRef.value.openDialogByBatchAdd(selectedIdList);
  else ElMessage.error('未勾选任何数据');
}

const onBatchStop = () => {
  ElMessage({ showClose: true, message: '勾选需要停录的课程后，再点击一键停选', type: 'success', duration: 10000 })
  selectType.value = 'stop'
}

const onOneKeyStop = () => {
  if (selectedIdList.length !== 0)
    ElMessageBox.confirm('您将停录勾选的课程,确定继续吗?', '提示', { type: 'warning' }).then(() => {
      stopCourse();
      selectType.value = ''
    }).catch(() => { });
  else ElMessage.error('未勾选任何数据');
}

const exitSelect = () => {
  selectType.value = ''
}

const onStop = (row: ICourse) => {
  ElMessageBox.confirm('您将停录勾选的课程,确定继续吗?', '提示', { type: 'warning' }).then(async () => {
    const data: ICoManageParams = {
      courseId: row.id,
      beginTime: baseTime,
      endTime: baseTime  //将时间设置为格林威治时间来停止
    }
    const res: APIData = await api.scManage.save(data);
    if (res.code === 200) {
      ElMessage.success('停录成功');
      getPageInfo();
    }
    else ElMessage.error(res.message);
  }).catch(() => { });
}

//勾选(仅收集勾选数据)
const onSeleceChange = (rowList: ICourse[]) => {
  // console.log('onSeleceChange',rowList);
  selectedIdList = [] as Array<string>;
  rowList.forEach(item => {
    selectedIdList.push(item.id);
  });
};

//判断哪些需要禁用
const selectTable = (row: ICourse, index: any) => {
  if (selectType.value == 'stop') {
    if (row.scoreIsBegin == 1) return true;
    else return false;
  } else if (selectType.value == 'begin') {
    if (row.scoreIsBegin != 1) return true;
    else return false;
  } else {
    return true;
  }
}

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  pageQuery.pageParams.pageNum = 1;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

const findAllCourseSchoolYear = async () => {
  const res: APIData = await api.course.findAllCourseSchoolYear();
  if (res.code == 200) {
    const originList = res.data;
    schoolYearList.value = originList.map((item: string) => {
      return { label: `${item}学年`, value: `${item}` }
    })
  }
};

const getPageInfo = async () => {
  const res = await api.course.findPage(pageQuery);
  tableData.value = res.data;
};

//一键停课请求
const stopCourse = async () => {
  const data: ICoManageList = {
    courseIdList: selectedIdList,
    beginTime: baseTime,
    endTime: baseTime  //将时间设置为格林威治时间来停止
  };
  const res = await api.scManage.saveBatch(data);
  if (res.data) {
    ElMessage({
      type: 'success',
      message: '一键停录成功',
    });
    getPageInfo();
  }
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  padding: 14px 32px;

  .searchBox {
    padding-top: 16px;
    &-item {
      margin-right: 10px;
    }

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }

    section {
      display: flex;
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }

  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }
  }
}
</style>
